﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;

namespace FitNesseRunner
{
	internal class IncludeHandler
	{
		private readonly string[] _content;
		private readonly Context _context;

		public IncludeHandler(string[] content, Context context)
		{
			_content = content;
			_context = context;
		}

		public IEnumerable<string> GetAllLines()
		{
			foreach (var line in _content)
			{
				var includedFilename = GetIncludedFilename(line);
				if (includedFilename == null)
					yield return line;
				else
				{
					var includedLines = File.ReadAllLines(includedFilename);
					var nestedIncludeHandler = new IncludeHandler(includedLines, _context);
					foreach (var includedLine in nestedIncludeHandler.GetAllLines())
					{
						yield return includedLine;
					}
				}
			}
		}

		private string GetIncludedFilename(string line)
		{
			const string beginningOfLine = "^";
			const string optionalWhitespace = @"\s*";
			const string mandatoryWhitespace = @"\s+";
			const string anyWordCharacter = @"\w";
			const string referenceGroupName = "reference";
			const string pattern = beginningOfLine + optionalWhitespace + @"\!include" + mandatoryWhitespace + "(-c?" + mandatoryWhitespace + ")(?<" + referenceGroupName + ">[" + anyWordCharacter + ".]+)";
			var match = new Regex(pattern).Match(line);
			if (!match.Success)
				return null;

			var reference = match.Groups[referenceGroupName].Value;
			var parts = reference.Split(new[]{'.'}, StringSplitOptions.RemoveEmptyEntries);
			var folderPath = Path.Combine(_context.RootPath, string.Join("\\", parts));
			return Path.Combine(folderPath, "content.txt");
		}
	}
}